package main

import (
	"context"
	"gdmin/api"
	"gdmin/config"
	"gdmin/db"
	_ "gdmin/docs"
	"gdmin/log"
	"gdmin/middleware"
	"gdmin/model"
	"gdmin/validate"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/middlewares/server/recovery"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
	"github.com/cloudwego/hertz/pkg/route"
	"github.com/google/uuid"
	"github.com/hertz-contrib/gzip"
	"github.com/hertz-contrib/logger/accesslog"
	"github.com/hertz-contrib/requestid"
	"github.com/hertz-contrib/swagger"
	swaggerFiles "github.com/swaggo/files"
)

// @title gadmin
// @version 1.0
// @description 基于Hertz开发的后台管理系统

// @contact.name HuiFer
// @contact.url https://github.com/hertz-contrib

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @host localhost:8888
// @BasePath /api
// @schemes http
func main() {
	initProfile()

	middleware.InitJwt()

	h := server.New(server.WithHostPorts(":8888"), server.WithValidateConfig(validate.InitValidate()))

	h.Use(middleware.Cors())
	h.Use(
		// 自定义 request id 生成逻辑
		requestid.New(requestid.WithGenerator(func(ctx context.Context, c *app.RequestContext) string {
			return uuid.New().String()
		}), // 自定义 request id 响应头键值
			requestid.WithCustomHeaderStrKey("request-id")))

	// gzip
	h.Use(gzip.Gzip(gzip.DefaultCompression))
	h.Use(middleware.TokenHandler)
	h.Use(recovery.Recovery(recovery.WithRecoveryHandler(middleware.HandlerError)))
	h.Use(accesslog.New(accesslog.WithFormat("[${time}] ${status} - ${latency} ${method} ${path} ${queryParams}")))
	h.Use(middleware.MyMiddleware())
	h.GET("/swagger/*any", swagger.WrapHandler(swaggerFiles.Handler))

	h.POST("api/user/login", middleware.JwtMiddleware.LoginHandler)
	auth := h.Group("/api", middleware.JwtMiddleware.MiddlewareFunc())
	auth.GET("/ping", middleware.Ping)
	auth.POST("/user/logout", middleware.JwtMiddleware.LogoutHandler)
	//v1 := h.Group("/")

	initApi(auth)
	h.POST("/beat", beat)

	hlog.Info("项目启动成功")

	h.Spin()
}

func beat(c context.Context, ctx *app.RequestContext) {

	ctx.JSON(consts.StatusOK, utils.H{"message": "pong"})
}

func initApi(h *route.RouterGroup) {
	api.BeatApi(h)
	api.UserApi(h)
	api.DeptApi(h)
	api.UserBindApi(h)
	api.RoleApi(h)
	api.ResApi(h)
	api.DictApi(h)
	api.FileApi(h)
	api.LogApi(h)

}
func initProfile() {
	config.InitSetting()
	mode := config.Setting.Mode
	log.InitLog(mode)
	db.Init(config.Setting.Db)

	model.InitDatabase()
}
